#include "TServer.h"
#include <stdio.h>
#include <iostream>
#include <algorithm>
TServer::TServer()
{

}

TServer::~TServer()
{

}
#define IO_THREAD_COUNT	2
#define BS_THREAD_COUNT 2

void TServer::Start(char* host, int port)
{
    serSock_.Listen(host, port);
    ioThreadPool.Start(IO_THREAD_COUNT);
    bsThreadPool.Start(BS_THREAD_COUNT);
    for (int i = 0; i < IO_THREAD_COUNT; i++)
        ioThreadPool.Run(std::bind(&TEventLoop::RunLoop, &eventLoop_[i], this));
    while (true)
    {
        TSocket* cli = serSock_.Accept();
        cli->SetNonBlock(true);
        OnConn(cli);
        eventLoop_[cli->fd() % IO_THREAD_COUNT].AddLoop(cli);
    }
}

void TServer::OnConn(TSocket* sock)
{
    printf("TServer::OnConn() is called, sock: %d conn\n", sock->fd());
}

void TServer::OnRecv(TSocket* sock)
{

}

void TServer::OnSend(TSocket* sock)
{

}

void TServer::OnClose(TSocket* sock)
{
    printf("TServer::OnClose() is called, sock: %d quit\n", sock->fd());
}

void TServer::PreRecv(TSocket* sock)
{
    //std::cout << "thread[" << std::this_thread::get_id() << "] recv socket[" << sock->fd() <<"] message" << std::endl;
    char buff[1024] = {0};
    int len = sock->Recv(buff, 1024);
    if (len > 0)
    {
        sock->Send(buff, len);
    }
    else
    {
        OnClose(sock);
        eventLoop_[sock->fd() % IO_THREAD_COUNT].DelLoop(sock);
        sock->Close();
    }

}